package itsen.com.bduidemo.modle.md.al3;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;

import itsen.com.bduidemo.R;
import itsen.com.bduidemo.lib.tool.LogTool;

/**
 * Created by Zhoudesen
 * Created time 2018/1/29 16:20
 * Description: Xfermode Path之贝塞尔曲线 应用
 * Version: V 1.0
 */

public class XfPathView extends View {
    /**
     * 圆形画笔
     */
    private Paint mPaintRound;
    /**
     * 水波纹画笔
     */
    private Paint mPaintWave;
    /**
     * 最小宽度
     */
    private final static int MIN_WIDTH = 300;
    /**
     * 最小高度
     */
    private final static int MIN_HEIGHT = 300;
    /**
     * 水波纹 背景颜色
     */
    private int mColorBgWave;
    /**
     * 水波纹 默认颜色
     */
    private final static int COLOR_BG_WAVE_DEFUALT = 0xaa00ff00;
    /**
     * 圆形boder颜色
     */
    private int mColorBgRoundBoder;
    /**
     * 圆形背景颜色
     */
    private int mColorBgRound;
    /**
     * 圆形 默认颜色 完全透明色
     */
    private final static int COLOR_BG_ROUND_DEFUALT = 0x00FFFFFF;
    /**
     * y 轴百分比
     */
    private float mPercentY = 0f;
    /**
     * 最大完成值
     */
    private float mPercentMax;
    /**
     * 1/2 波峰x轴长度（每个波峰/波谷均为贝塞尔曲线的控制点）
     */
    private float mRadius;
    /**
     * x 轴偏移量（让水波纹动起来）
     */
    private float mDx = 0;
    /**
     * y 轴波峰突出值（波谷凹陷值）
     */
    private int mDy = 0;
    /**
     * view高宽值（高=宽）
     */
    private int mViewWidthHeight;

    private Path mPath;

    private Bitmap mBitmap;

    private ValueAnimator mAnimator;

    private PorterDuffXfermode mPorterDuffXfermode;

    private RectF mRectf;

    public XfPathView(Context context) {
        this(context, null);
    }

    public XfPathView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public XfPathView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    /**
     * 初始化参数
     *
     * @param context
     * @param attrs
     */
    private void init(Context context, AttributeSet attrs) {
        if (attrs != null) {
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.XFPView);
            mColorBgRound = typedArray.getColor(R.styleable.XFPView_backgroundColorRound, COLOR_BG_ROUND_DEFUALT);
            mColorBgRoundBoder = typedArray.getColor(R.styleable.XFPView_backgroundColorRoundBoder, COLOR_BG_WAVE_DEFUALT);
            mColorBgWave = typedArray.getColor(R.styleable.XFPView_backgroundColorWave, COLOR_BG_WAVE_DEFUALT);
            mPercentMax = typedArray.getFloat(R.styleable.XFPView_percentMax, 100);
            mDy = typedArray.getInteger(R.styleable.XFPView_waveDy, 20);
            typedArray.recycle();
        }

        mPath = new Path();
        //画笔初始化
        mPaintRound = new Paint();
        mPaintRound.setAntiAlias(true);
        mPaintRound.setStyle(Paint.Style.STROKE);
        mPaintRound.setStrokeWidth(3);
        mPaintRound.setColor(mColorBgRoundBoder);

        mPaintWave = new Paint();
        mPaintWave.setAntiAlias(true);
        mPaintWave.setColor(mColorBgWave);
        mPaintWave.setStyle(Paint.Style.FILL);

        mPorterDuffXfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);

        mRectf = new RectF(0,0,mViewWidthHeight,0);

        setmPercentY(10);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int height = 0;
        int width = 0;
        if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY) {
            width = MeasureSpec.getSize(widthMeasureSpec);
        }
        if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY) {
            height = MeasureSpec.getSize(heightMeasureSpec);
        }
        //取最小值为view的高宽，让“高”=“宽”
        width = Math.min(width, height);

        if ( width > MIN_WIDTH) {
            setMeasuredDimension(width, width);
        } else {
            setMeasuredDimension(MIN_WIDTH, MIN_HEIGHT);
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mViewWidthHeight = w;
        //二分之一的波峰波谷
        mRadius = mViewWidthHeight / 4;
        if (mBitmap == null) {
            mBitmap = Bitmap.createBitmap(mViewWidthHeight, mViewWidthHeight, Bitmap.Config.ARGB_8888);
        }
        startAinm();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        //--画圆boder
        drawBoder(canvas);

        //--saveLayer
        int layerId = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG);

        //--画水波纹
        drawWave(canvas);

        canvas.restoreToCount(layerId);
    }

    private void drawBoder(Canvas canvas){
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, mViewWidthHeight / 2 - 1, mPaintRound);
    }

    private void drawWave(Canvas canvas){
        //--画圆心
        mPaintWave.setColor(mColorBgRound);
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, (mViewWidthHeight / 2) - 3, mPaintWave);

        //--画水波纹
        mPath.reset();
        mPath.moveTo(0 - mDx, mPercentY * mViewWidthHeight);
        //四个点
        for (int i = 0; i < 4; i++) {
            mDy = -mDy;
            mPath.quadTo((1 + 2 * i) * mRadius - mDx, mPercentY * mViewWidthHeight + mDy,
                    (1 + i) * 2 * mRadius - mDx, mPercentY * mViewWidthHeight);
        }
        //连接到右边view底部
        mPath.lineTo(2 * mViewWidthHeight - mDx, mViewWidthHeight);
        //连接到左边底部
        mPath.lineTo(0 - mDx, mViewWidthHeight);
        //闭合
        mPath.close();

        //--圆与水波纹fix
        mPaintWave.setColor(mColorBgWave);
        mPaintWave.setXfermode(mPorterDuffXfermode);
        canvas.drawPath(mPath, mPaintWave);

        //--用完全透明的矩形消除圆的上部分
        mPaintWave.setColor(COLOR_BG_ROUND_DEFUALT);
        mRectf.right = mViewWidthHeight;
        mRectf.bottom = mViewWidthHeight * mPercentY - mDy;
        canvas.drawRect(mRectf, mPaintWave);

        mPaintWave.setXfermode(null);
    }
    /**
     * 初始化并开始动画
     */
    public void startAinm() {
        mAnimator = ValueAnimator.ofFloat(0, mViewWidthHeight);
        mAnimator.setDuration(2000);
        mAnimator.setInterpolator(new LinearInterpolator());
        mAnimator.setRepeatCount(ValueAnimator.INFINITE);
        mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mDx = (float) animation.getAnimatedValue();
                postInvalidate();
            }
        });
        mAnimator.start();
    }


    /**
     * 暂停
     */
    public void stopAnim() {
        if (mAnimator.isStarted()) {
            mAnimator.pause();
        }
    }

    /**
     * 重启
     */
    public void reStartAinm() {
        if (mAnimator != null && mAnimator.isPaused()) {
            mAnimator.start();
        }
    }

    /**
     * 设置完成度
     *
     * @param value
     */
    public void setmPercentY(float value) {
        this.mPercentY = 1 - (value / mPercentMax < 1 ? value / mPercentMax : 1);
    }
}
